package concurrencyPractice.chapter06;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author xinya
 * @version 1.0
 * @project javacore
 * @description 6-14 使用 Future 等待图像下载
 * @date 2024/1/3 17:12:33
 */
public class FutureRenderer {
    private final ExecutorService executor = Executors.newFixedThreadPool(100);

    void renderPage(CharSequence source) {
        final List<ImageInfo> imageInfos = scanForImageInfo(source);
        Callable<List<ImageData>> task = new Callable<List<ImageData>>() {
            @Override
            public List<ImageData> call() throws Exception {
               List<ImageData> result = new ArrayList<>();
                for (ImageInfo imageInfo: imageInfos
                     ) {
                    result.add(imageInfo.downloadImage());
                }
                return result;
            }
        };

        Future<List<ImageData>> future = executor.submit(task);
        renderText(source);

        try {
            List<ImageData> imageData = future.get();
            for (ImageData data: imageData) {
                renderImage(data);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            future.cancel(true);
        } catch (ExecutionException e) {
            throw launderThrowable(e.getCause());
        }

    }

    List<FutureRenderer.ImageInfo> scanForImageInfo (CharSequence charSequence) {
        return null;
    }

    final class ImageInfo {
        ImageData downloadImage() {
            return null;
        }
    }

    final class ImageData{

    }
}
